// virtualTradingUtils.js - 存放虚拟交易相关的工具函数

const VIRTUAL_TRADING_STATE_KEY = 'crypto_bot_virtual_trading_state'

/**
 * 保存虚拟交易状态
 * @param {Object} isVirtualTrading - 是否正在虚拟交易
 * @param {Object} virtualTradingResults - 虚拟交易结果
 * @param {Object} backtestSettings - 回测设置
 */
export const saveVirtualTradingState = (isVirtualTrading, virtualTradingResults, backtestSettings) => {
  try {
    // 数据验证
    if (!isVirtualTrading.value && virtualTradingResults.trades.length === 0) {
      console.log('没有需要保存的数据')
      return
    }
    
    const stateData = {
      isActive: isVirtualTrading.value,
      symbol: backtestSettings.symbol,
      strategy: backtestSettings.strategyType,
      startTime: new Date().toISOString(),
      cash: virtualTradingResults.cash,
      position: virtualTradingResults.position,
      totalValue: virtualTradingResults.totalValue,
      currentPrice: virtualTradingResults.currentPrice,
      pnl: virtualTradingResults.pnl,
      pnlPercent: virtualTradingResults.pnlPercent,
      trades: virtualTradingResults.trades,
      priceHistory: virtualTradingResults.priceHistory.slice(-50), // 只保存最近50个价格点
      lastSignalTime: virtualTradingResults.lastSignalTime,
      // 风险控制状态
      maxDrawdownReached: virtualTradingResults.maxDrawdownReached,
      currentDrawdown: virtualTradingResults.currentDrawdown,
      riskLocked: virtualTradingResults.riskLocked,
      lastStopLoss: virtualTradingResults.lastStopLoss,
      lastTakeProfit: virtualTradingResults.lastTakeProfit,
      positionValue: virtualTradingResults.positionValue,
      riskEvents: virtualTradingResults.riskEvents.slice(-10), // 只保存最近10个风险事件
      // 当前会话交易跟踪
      currentSessionTradesCount: virtualTradingResults.currentSessionTradesCount,
      sessionStartTime: virtualTradingResults.sessionStartTime,
      settings: {
        symbol: backtestSettings.symbol, // 添加交易对保存
        initialCapital: backtestSettings.initialCapital,
        tradeAmount: backtestSettings.tradeAmount,
        fastMAPeriod: backtestSettings.fastMAPeriod,
        slowMAPeriod: backtestSettings.slowMAPeriod,
        rsiPeriod: backtestSettings.rsiPeriod,
        overbought: backtestSettings.overbought,
        oversold: backtestSettings.oversold,
        bbPeriod: backtestSettings.bbPeriod,
        bbStdDev: backtestSettings.bbStdDev,
        stopLoss: backtestSettings.stopLoss,
        takeProfit: backtestSettings.takeProfit,
        maxPosition: backtestSettings.maxPosition,
        riskControl: backtestSettings.riskControl,
        maxDrawdownLimit: backtestSettings.maxDrawdownLimit,
        strategyType: backtestSettings.strategyType, // 添加策略类型保存
        period: backtestSettings.period, // 添加周期保存
        interval: backtestSettings.interval, // 添加K线周期保存
        dataSource: backtestSettings.dataSource, // 添加数据源保存
        // AI智能策略1参数
        mlConfidenceThreshold: backtestSettings.mlConfidenceThreshold,
        mlFeatureWeighting: backtestSettings.mlFeatureWeighting,
        mlMarketStateAware: backtestSettings.mlMarketStateAware,
        mlDynamicPositioning: backtestSettings.mlDynamicPositioning,
        mlSentimentWeight: backtestSettings.mlSentimentWeight,
        mlAdaptiveStopLoss: backtestSettings.mlAdaptiveStopLoss,
        // 新增高级AI参数
        mlRiskFilter: backtestSettings.mlRiskFilter,
        mlSignalThreshold: backtestSettings.mlSignalThreshold,
        mlMultiFactorMode: backtestSettings.mlMultiFactorMode
      },
      lastUpdated: new Date().toISOString(),
      version: '2.0' // 版本标识
    }
    
    // 检查数据大小（限制在5MB以内）
    const dataSize = JSON.stringify(stateData).length
    const maxSize = 5 * 1024 * 1024 // 5MB
    
    if (dataSize > maxSize) {
      console.warn(`状态数据过大（${(dataSize / 1024 / 1024).toFixed(2)}MB），精简数据`)
      // 精简数据
      stateData.trades = stateData.trades.slice(-100) // 只保存最近100笔交易
      stateData.priceHistory = stateData.priceHistory.slice(-30) // 只保存最近30个价格点
      stateData.riskEvents = stateData.riskEvents.slice(-5) // 只保存最近5个风险事件
    }
    
    localStorage.setItem(VIRTUAL_TRADING_STATE_KEY, JSON.stringify(stateData))
    console.log(`✅ 虚拟交易状态已保存（${(dataSize / 1024).toFixed(1)}KB）`)
  } catch (error) {
    console.error('❌ 保存虚拟交易状态失败:', error)
    
    // 尝试清理旧数据后重试
    try {
      localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
      console.log('已清理旧状态数据')
    } catch (cleanupError) {
      console.error('清理旧状态数据失败:', cleanupError)
    }
  }
}

/**
 * 加载虚拟交易状态
 * @returns {Object|null} 状态数据或null
 */
export const loadVirtualTradingState = () => {
  try {
    const stateJson = localStorage.getItem(VIRTUAL_TRADING_STATE_KEY)
    if (!stateJson) {
      console.log('⚠️ 未找到保存的虚拟交易状态')
      return null
    }
    
    const stateData = JSON.parse(stateJson)
    
    // 版本兼容性检查
    const version = stateData.version || '1.0'
    if (version !== '2.0') {
      console.log('旧版本数据，将进行升级')
      return migrateOldStateData(stateData)
    }
    
    // 验证状态数据完整性
    const requiredFields = ['isActive', 'symbol', 'strategy', 'cash', 'position', 'totalValue']
    const missingFields = requiredFields.filter(field => !(field in stateData))
    
    if (missingFields.length > 0) {
      console.error('❌ 状态数据不完整，缺少字段:', missingFields)
      return null
    }
    
    // 数据合理性检查
    if (stateData.cash < 0 || stateData.position < 0 || stateData.totalValue < 0) {
      console.error('❌ 状态数据包含负值，可能已损坏')
      return null
    }
    
    // 检查数据时效性（24小时内的数据才有效）
    const lastUpdated = new Date(stateData.lastUpdated)
    const now = new Date()
    const hoursDiff = (now - lastUpdated) / (1000 * 60 * 60)
    
    if (hoursDiff > 24) {
      console.log(`⚠️ 状态数据过旧（${hoursDiff.toFixed(1)}小时前），建议清理`)
      // 不返回null，但给出警告
    }
    
    console.log('✅ 虚拟交易状态加载成功')
    console.log(`📅 最后更新: ${stateData.lastUpdated}`)
    console.log(`💰 当前盈亏: ${stateData.pnlPercent?.toFixed(2) || 0}%`)
    return stateData
  } catch (error) {
    console.error('❌ 加载虚拟交易状态失败:', error)
    
    // 尝试清理损坏的数据
    try {
      localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
      console.log('已清理损坏的状态数据')
    } catch (cleanupError) {
      console.error('清理损坏数据失败:', cleanupError)
    }
    
    return null
  }
}

/**
 * 迁移旧版本数据
 * @param {Object} oldData - 旧数据
 * @returns {Object} 迁移后的数据
 */
const migrateOldStateData = (oldData) => {
  try {
    console.log('开始迁移旧版本数据...')
    
    const migratedData = {
      ...oldData,
      version: '2.0',
      // 添加新字段的默认值
      maxDrawdownReached: oldData.maxDrawdownReached || 0,
      currentDrawdown: oldData.currentDrawdown || 0,
      riskLocked: oldData.riskLocked || false,
      lastStopLoss: oldData.lastStopLoss || null,
      lastTakeProfit: oldData.lastTakeProfit || null,
      positionValue: oldData.positionValue || 0,
      riskEvents: oldData.riskEvents || [],
      settings: {
        ...oldData.settings,
        symbol: oldData.symbol || oldData.settings?.symbol || 'BTC/USDT', // 恢复交易对
        strategyType: oldData.strategy || oldData.settings?.strategyType || 'ma_cross', // 恢复策略类型
        period: oldData.settings?.period || '30d',
        interval: oldData.settings?.interval || '1d',
        dataSource: oldData.settings?.dataSource || 'real',
        maxPosition: oldData.settings?.maxPosition || 80,
        riskControl: oldData.settings?.riskControl !== undefined ? oldData.settings.riskControl : true,
        maxDrawdownLimit: oldData.settings?.maxDrawdownLimit || 15
      }
    }
    
    // 保存迁移后的数据
    localStorage.setItem(VIRTUAL_TRADING_STATE_KEY, JSON.stringify(migratedData))
    console.log('✅ 数据迁移完成')
    
    return migratedData
  } catch (error) {
    console.error('❌ 数据迁移失败:', error)
    return null
  }
}

/**
 * 恢复虚拟交易状态
 * @param {Object} stateData - 状态数据
 * @param {Object} isVirtualTrading - 是否正在虚拟交易
 * @param {Object} virtualTradingResults - 虚拟交易结果
 * @param {Object} backtestSettings - 回测设置
 * @returns {boolean} 是否成功
 */
export const restoreVirtualTradingState = (stateData, isVirtualTrading, virtualTradingResults, backtestSettings) => {
  try {
    // 恢复交易设置（包括交易对信息）
    if (stateData.settings) {
      Object.assign(backtestSettings, stateData.settings)
    }
    
    // 兼容性处理：从外层symbol字段恢复交易对（针对旧版本数据）
    if (stateData.symbol && !stateData.settings?.symbol) {
      backtestSettings.symbol = stateData.symbol
    }
    
    // 兼容性处理：从外层strategy字段恢复策略类型（针对旧版本数据）
    if (stateData.strategy && !stateData.settings?.strategyType) {
      backtestSettings.strategyType = stateData.strategy
    }
    
    console.log(`🔄 恢复交易对: ${backtestSettings.symbol}, 策略: ${backtestSettings.strategyType}`)
    
    // 恢复虚拟交易数据
    Object.assign(virtualTradingResults, {
      cash: stateData.cash || 0,
      position: stateData.position || 0,
      totalValue: stateData.totalValue || 0,
      currentPrice: stateData.currentPrice || 0,
      pnl: stateData.pnl || 0,
      pnlPercent: stateData.pnlPercent || 0,
      trades: stateData.trades || [],
      priceHistory: stateData.priceHistory || [],
      lastSignalTime: stateData.lastSignalTime || 0,
      // 恢复当前会话交易计数器（重新开始计数）
      currentSessionTradesCount: 0, // 重新开始计数当前会话
      sessionStartTime: new Date().toISOString() // 记录新会话开始时间
    })
    
    // 恢复虚拟交易状态
    if (stateData.isActive) {
      isVirtualTrading.value = true
    }
    
    return true
  } catch (error) {
    console.error('❌ 恢复虚拟交易状态失败:', error)
    return false
  }
}

/**
 * 清理虚拟交易状态
 */
export const clearVirtualTradingState = () => {
  try {
    localStorage.removeItem(VIRTUAL_TRADING_STATE_KEY)
    console.log('🗑️ 虚拟交易状态已清理')
  } catch (error) {
    console.error('❌ 清理虚拟交易状态失败:', error)
  }
}